package com.taotao.manage.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.management.loading.PrivateClassLoader;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.abel533.mapper.Mapper;
import com.taotao.common.service.RedisService;
import com.taotao.common.utils.ItemCatData;
import com.taotao.common.utils.ItemCatResult;
import com.taotao.manage.mapper.ItemCatMapper;
import com.taotao.manage.pojo.ItemCat;

@Service
public class ItemCatService extends BaseService<ItemCat>{

	/**
	 * 全部查询，并生成树状结构
	 * @return
	 */
	@Autowired
	private RedisService redisService;

	private static final ObjectMapper objectMapper = new ObjectMapper();
	private static final Integer REDIS_TIEM = 60*60*24*30*3;
	private static final String KEY="TAOTAO_MANAGE_ITEM_CAT_ALL";  //规则：项目名_模块名_业务名
	private static final Logger LOGGER = LoggerFactory.getLogger(ItemCatService.class);
	public ItemCatResult queryAllToTree() {
		
		//先从缓存中查找，没有再继续查询      
		try {
		String cacheDate = this.redisService.get(KEY);
		if (StringUtils.isNotEmpty(cacheDate)) {
			//反序列化
				return objectMapper.readValue(cacheDate, ItemCatResult.class);
			}
			}catch (Exception e) {
				// TODO Auto-generated catch block
				LOGGER.debug("缓存出错！",e);
			}
		ItemCatResult result = new ItemCatResult();
		//全部查出，并在内存中生成树形结构
		List<ItemCat> cats = super.queryAll();
		
		//转为map存储，key为父节点Id,value为数据集合
		Map<Long, List<ItemCat>> itemCatMap = new HashMap<Long,List<ItemCat>>();
		for (ItemCat itemCat : cats) {
			if (!itemCatMap.containsKey(itemCat.getParentId())) {
				itemCatMap.put(itemCat.getParentId(), new ArrayList<ItemCat>());
			}
			itemCatMap.get(itemCat.getParentId()).add(itemCat);
		}
		
		//封装一级对象
		List<ItemCat> itemCatList = itemCatMap.get(0L);
		for (ItemCat itemCat : itemCatList) {
			ItemCatData itemCatData = new ItemCatData();
			itemCatData.setUrl("/products/"+itemCat.getId()+".html");
			itemCatData.setName("<a href='"+itemCatData.getUrl()+"'>"+itemCat.getName()+"</a>");
			result.getItemCats().add(itemCatData);
			System.out.println();
			if (!itemCat.getIsParent()) {
				continue;
			}
			//封装二级对象
			List<ItemCat> itemCatList2 = itemCatMap.get(itemCat.getId());
			List<ItemCatData> itemCatData2 = new ArrayList<ItemCatData>();
			itemCatData.setItems(itemCatData2);
			for (ItemCat itemCat2 : itemCatList2) {
				ItemCatData id2 = new ItemCatData();
				id2.setName(itemCat2.getName());
				id2.setUrl("/products/"+itemCat2.getId()+".html");
				itemCatData2.add(id2);
				if (itemCat2.getIsParent()) {
					 // 封装三级对象
                    List<ItemCat> itemCatList3 = itemCatMap.get(itemCat2.getId());
                    List<String> itemCatData3 = new ArrayList<String>();
                    id2.setItems(itemCatData3);
                    for (ItemCat itemCat3 : itemCatList3) {
                        itemCatData3.add("/products/" + itemCat3.getId() + ".html|" + itemCat3.getName());
                    }
				}
			}
			 if (result.getItemCats().size() >= 14) {
	                break;
	            }
		}
		
		//将结果集传入到缓存redis中
		try {
			this.redisService.set(KEY, objectMapper.writeValueAsString(result), REDIS_TIEM);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
			
	}
	
	
	
/*	@Override
	public Mapper<ItemCat> getMapper() {
		// TODO Auto-generated method stub
		return this.itemCatMapper;
	}*/
	
/*	@Autowired
	private ItemCatMapper itemCatMapper;*/

/*	public List<ItemCat>  queryItemCatListByparentId(long parentId) {
		// TODO Auto-generated method stub
		//根据父节点id查询类目数据
		ItemCat itemCat = new ItemCat();
		itemCat.setParentId(parentId);
		return this.itemCatMapper.select(itemCat);
		
	}*/


}
